package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author 34633
 */
@RestController
@RequestMapping("/edumsm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 阿里云发送验证码 ！！！停用
     * @param phone
     * @return
     */
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //生成随机值,传递给阿里云/短信宝进行发送
        String code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code",code);

        //调用service发送短信的方法
        boolean isSend = msmService.send(param,phone);
        if (isSend){
            return R.ok();
        }else {
            return R.error().message("短信发送失败");
        }


    }

    /**
     * 短信宝发送验证码
     * @param phone
     * @return
     */
    @GetMapping("send_dxb/{phone}")
    public R sendDxbMsm(@PathVariable String phone){
        //1.先从redis中取验证码,如果能获取到就直接返回,如果获取不到就发送
        String code = redisTemplate.opsForValue().get("phone");
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }

        //生成随机值,传递给阿里云/短信宝进行发送
        code = RandomUtil.getFourBitRandom();

        //调用service发送短信的方法
        boolean isSend = msmService.sendDxb(code,phone);
        if (isSend){
            //发送成功,把发送成功验证码放到redis里面,设置有效时间3分钟
            redisTemplate.opsForValue().set(phone,code,10, TimeUnit.MINUTES);
            return R.ok().message("短信发送成功");
        }else {
            return R.error().message("短信发送失败");
        }


    }



}
